<template>
  <div class="about-master-container">
    <base-breadcrumb :breadcrumb="!isAudit">
      <b-steps
        :current="stepVal"
        direction="vertical"
        @change.self="stepChange"
      >
        <b-step title="基本信息">
          <a-card
            v-show="activeKey[0]"
            slot="description"
            v-loading="loading"
            :bordered="false"
          >
            <a-form-model
              ref="ruleForm"
              :model="form"
              :rules="rules"
            >
              <a-row>
                <a-col :span="8">
                  <a-form-model-item label="物资设备采购计划编码">
                    <BaseInput
                      v-model="form.purchaseCode"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item
                    label="项目名称"
                    prop="projectCode"
                  >
                    <SelectDownProject
                      v-model="form.projectCode"
                      :disabled="state === 3"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item
                    label="编号"
                    prop="code"
                  >
                    <BaseInput
                      v-model="form.code"
                      :disabled="state === 3"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="创建人">
                    <BaseInput
                      v-model="form.creatorName"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="创建时间">
                    <BaseInput
                      v-model="form.createTime"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form-model>
            <div
              v-if="!isAudit"
              class="pub-next-btn"
            >
              <a-button
                v-if="state !== 3"
                type="primary"
                @click="temporaryStorage()"
              >
                保存草稿
              </a-button>
              <a-button
                type="primary"
                @click="temporaryStorage(true)"
              >
                下一步
              </a-button>
            </div>
          </a-card>
        </b-step>
        <b-step title="物资设备采购策划表">
          <a-card
            v-if="activeKey[1]"
            slot="description"
            :bordered="false"
          >
            <materailPlanTable
              :id="form.id"
              ref="material"
              :state="state"
              :project-id="form.projectId"
            />
            <div
              v-if="!isAudit"
              class="pub-next-btn"
            >
              <a-button
                type="primary"
                @click="previous"
              >
                上一步
              </a-button>
              <a-button
                type="primary"
                @click="next"
              >
                下一步
              </a-button>
            </div>
          </a-card>
        </b-step>
        <b-step title="相关附件">
          <a-card
            v-if="activeKey[2]"
            slot="description"
            :bordered="false"
          >
            <u-table
              :upload-list="addFile"
              :delete-url="fileDel"
              :is-show="state !== 3"
              :list-url="fileList"
              :business-id="form.id"
              business-code="MM08"
            />
            <div
              v-if="!isAudit"
              class="pub-next-btn"
            >
              <a-button
                type="primary"
                @click="previous"
              >
                上一步
              </a-button>
            </div>
          </a-card>
        </b-step>
      </b-steps>
      <div
        v-if="!isAudit"
        class="pub-header-btn"
      >
        <a-button
          v-if="state !== 3"
          :loading="loading"
          type="primary"
          @click="submit"
        >
          提交
        </a-button>
        <BasePrintButton
          v-if="form.id && state == 3"
          :before-print-fn="beforePrintFn"
          style="display: inline-block"
        />
        <a-button
          v-checkVisibleInDetail
          @click="$close"
        >
          关闭
        </a-button>
      </div>
    </base-breadcrumb>
  </div>
</template>

<script>
import { themeChoose } from '@/mixin/mixin'
import materailPlanTable from '../components/materialPlan' // 物资需用
import { getNowTime } from '@/api/basePage'
import {
  equipmentPurchaseAddBasic,
  equipmentPurchaseEditBasic,
  audit,
  addFile,
  fileList,
  fileDel,
  equipmentPurchaseBasicInfo,
  print
} from '@/api/material/materialMasterPlan/equipmentPurchasePlan'
import SelectDownProject from '@/components/Select/SelectDownProject'

export default {
  // name:'a'+Date.now(),
  mixins: [themeChoose],
  components: {
    materailPlanTable,
    SelectDownProject
  },
  props: {
    isAudit: {
      // 是否作为审批详情
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      activeKey: [true, false, false, false, false, false, false],
      loading: false,
      allList: [], // 全部明细
      // project:[{"code":"641898837274927104","name":"孵化园改建2020"},{"code":"641897557404033024","name":"孵化园改建"}],
      reberData: [], // 钢筋需用列表
      concreteData: [], // 混凝土
      materialData: [], // 物资需用计划
      toolsData: [], //周转工具
      // editId: this.$route.query.id,
      isDetails: this.$route.query.isDetails,
      // isAdd: this.$route.query.type,
      form: {
        purchaseCode: '',
        projectCode: '',
        projectName: '',
        code: '',
        creatorName: JSON.parse(sessionStorage.getItem('ycloud-user_info')).name,
        createTime: this.getNowTime()
      },
      titleName: '',
      projectOldId: '', // 刚进来的项目id
      state: ~~this.$route.query.state,
      isSubmit: false,
      row: this.$route.query.row,
      stepVal: 0,
      isNext: false,
      rules: {
        projectCode: { required: true, message: '项目名称不能为空', trigger: 'change' },
        code: { required: true, message: '编号不能为空', trigger: 'blur' }
      },
      addFile: addFile(),
      fileDel: fileDel(),
      fileList: fileList(),
      beforePrintFn: async () => {
        let res = await print({ id: this.form.id })
        // res.data = res.data.replaceAll('\n', '\\')
        return res.data.content
      }
    }
  },
  watch: {
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.state = 3
        }
      }
    },
    stepVal(newVal, oldVal) {
      this.$set(this.activeKey, newVal, true)
    }
  },
  mounted() {
    if (this.state === 1) {
      this.form.createTime = getNowTime()
    } else {
      this.form.id = this.$route.query.id
      this.getEditInfo()
      this.isSubmit = true
    }
  },
  methods: {
    projectChange(val) {
      this.project.map((item) => {
        if (this.form.projectCode === item.code) {
          this.form.projectName = item.name
        }
      })
    },
    next(val) {
      this.isNext = true
      this.stepVal++
    },
    previous() {
      this.isNext = true
      this.stepVal--
      if (this.stepVal < 0) {
        this.stepVal = 0
      }
    },
    stepChange(val) {
      if (!this.form.id && !this.isAudit) {
        // 作为审批详情时可跳过步骤
        if (val) {
          this.$message.warning('切换步骤前请先填写基本信息')
          this.stepVal = 0
        }
      } else {
        if (!this.isNext) {
          this.$set(this.activeKey, val, !this.activeKey[val])
        }
      }
      this.isNext = false
    },
    // 获取编辑回显数据
    async getEditInfo() {
      this.loading = true
      const res = await equipmentPurchaseBasicInfo({ id: this.form.id })
      if (res.code === 200) {
        this.form = { ...this.form, ...res.data }
        this.form.projectId = this.form.projectCode
      } else {
        this.$message.warning('获取信息失败')
      }
      this.loading = false
    },
    del() {
      this.delList(equipmentPurchaseDel, null, { ids: this.form.id })
    },
    /**
     * @description: 校验表格
     */
    async checkTable(resolve, reject) {
      //   if (this.allList.length === 0) {
      let List =
        (await new Promise((resolves, rejects) => {
          this.$refs.material?.getAll((res) => {
            resolves(res.data)
          })
        })) || []
      //   }
      if (List.length === 0) {
        this.$noticeWarning('物资设备采购策划表不能为空！')
        reject()
      }
      for (let index in List) {
        let page = Math.ceil((Number(index) + 1) / this.$refs.material?.$refs.table?.pageSize)
        let row = List[index]
        for (let key in this.$refs.material?.rules) {
          let value = this.$refs.material?.rules[key]
          if (this.$isEmpty(row[key])) {
            this.$noticeWarning(`《物资设备采购策划表》第${page}页第${Number(index) + 1}行：${value.message}`)
            reject()
            return
          }
        }
      }
      resolve()
    },
    submit() {
      if (this.isSubmit) {
        // 校验表格表单项
        new Promise((resolve, reject) => {
          this.checkTable(resolve, reject)
        }).then(() => {
          this.$submitConfirm(() => {
            this.loading = true
            audit({ baseId: this.form.id, auditStatus: this.form.auditStatus }).then((res) => {
              if (res.code === 200) {
                this.$message.success('提交成功')
                this.$router.push({ path: '/material/equipmentPurchasePlan' })
              }
              this.loading = false
            })
          })
        })
      } else {
        this.$message.warning('提交之前请先暂存')
      }
    },
    temporaryStorage(isNext) {
      if (this.state === 3) {
        this.next()
        return
      }
      this.$refs.ruleForm.validate(async (valid, object) => {
        if (valid) {
          this.loading = true
          if (this.state === 2 || this.form.id !== undefined) {
            let res = await equipmentPurchaseEditBasic(this.form)
            if (res.code === 200) {
              this.$message.success('暂存成功')
              this.isSubmit = true
              if (isNext) {
                this.next()
              }
            }
          } else {
            let res = await equipmentPurchaseAddBasic(this.form)
            if (res.code === 200) {
              this.$message.success('暂存成功')
              this.isSubmit = true
              this.form.id = res.data.id
              if (isNext) {
                this.next()
              }
              await this.getEditInfo()
            }
          }
          this.loading = false
        } else {
          this.$message.warning("请填写完所有必填项信息")
          return false
        }
      })
    }
  }
}
</script>

